package concurrency;


import sun.misc.Unsafe;

/**
 * jdk9后 Unsafe已经不能直接使用了，jdk内部通过VarHandler来使用Unsafe
 */
public class UnsafeDemo {
    private static Unsafe unsafe = Unsafe.getUnsafe();

    private static final long stateOffset;

    private volatile long state = 0;

    static {
        try {
            stateOffset = unsafe.objectFieldOffset(UnsafeDemo.class.getDeclaredField("state"));
        } catch (NoSuchFieldException e) {
            System.out.println(e.getLocalizedMessage());
            throw new Error(e);
        }
    }

    public static void main(String[] args) {
        UnsafeDemo unsafeDemo = new UnsafeDemo();
        Boolean success = unsafe.compareAndSwapInt(unsafeDemo, stateOffset, 0, 1);
        System.out.println(success);
    }
}
